package com.woniu.account.controller;

import cn.hutool.core.bean.BeanUtil;
import com.woniu.account.dto.User.UserAddressDto;
import com.woniu.account.model.UserAddress;
import com.woniu.account.param.User.UserAddressParam;
import com.woniu.account.service.UserAddressService;
import com.woniu.model.Result;
import com.woniu.util.JwtUtil;
import com.woniu.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月11日
 */
@RestController
@RequestMapping("/userAddress")
@Api(tags = "用户收货地址操作")
public class UserAddressController {
    @Resource
    private UserAddressService userAddressService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/addAddress")
    @ApiOperation("新增收货地址")
    public Result AddAddress(@RequestBody UserAddress  form,  @RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());//NullPointerException
        UserAddressParam param = BeanUtil.toBean(form,UserAddressParam.class);
        param.setUserId(userId);
        userAddressService.addAddress(param);
        return  Result.getResult().setMsg("地址添加成功");
    }


    @GetMapping("/selectAddress")
    @ApiOperation("加载个人所有收货地址")
    public Result<Object> selectAddress(@RequestHeader String token) throws Exception {//
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
        List<UserAddress> userAddresses = userAddressService.selectAddress(userId);
        return Result.getResult().setData(BeanUtil.copyToList(userAddresses, UserAddressDto.class));
    }

    @PostMapping("updateAddress")
    @ApiOperation("修改用户收货地址")
    public Result updateAddress(UserAddress form,@RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
          UserAddressParam param = BeanUtil.toBean(form,UserAddressParam.class);
          param.setUserId(userId);
          userAddressService.updateAddress(param);
        return Result.getResult().setMsg("修改用户地址成功");
    }

}

